<template>
    <div class="app-container" v-hasPermi="['fang:maintenance:add']">
      <!-- 添加或修改维保对话框 -->
      <el-dialog title="新建工单" v-model="open" width="800px" append-to-body>
        <el-form ref="maintenanceRef" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="20">
            <!-- 左列 -->
            <el-col :span="12">
              <!-- 房源信息 -->
              <el-form-item label="房源信息" prop="houseId">
                <HouseSelector
                  v-model="form.houseId"
                  placeholder="请选择房源"
                  @change="handleHouseChange"
                />
              </el-form-item>
              
              <!-- 简要描述 -->
              <el-form-item label="简要描述" prop="simpleDescription">
                <el-input v-model="form.simpleDescription" v-trim placeholder="请输入简要描述" />
              </el-form-item>

              <!-- 报修时间 -->
              <el-form-item label="报修时间" prop="repairCreateTime">
                <el-date-picker 
                  clearable
                  v-model="form.repairCreateTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择报修时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            
            <!-- 右列 -->
            <el-col :span="12">
              <!-- 租客 -->
              <el-form-item label="租客" prop="tenantUserId">
                <TenantSelector
                  v-model="form.tenantUserId"
                  placeholder="请选择租客"
                  @change="handleTenantChange"
                />
              </el-form-item>
              
              <!-- 手机号 -->
              <el-form-item label="手机号" prop="tenantUserPhone">
                <el-input v-model="form.tenantUserPhone" v-trim placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 详细描述 - 单独一行 -->
          <el-form-item label="详细描述" prop="detailDescription">
            <el-input 
              v-model="form.detailDescription" 
              v-trim
              type="textarea" 
              :rows="3"
              placeholder="管理员备注...." 
            />
          </el-form-item>
          
          <!-- 备注说明 - 单独一行 -->
          <el-form-item label="备注说明" prop="remark">
            <el-input 
              v-model="form.remark" 
              v-trim
              type="textarea" 
              :rows="3"
              placeholder="管理员备注...." 
            />
          </el-form-item>
          
          <!-- 附件 -->
          <el-form-item label="附件" prop="descriptionPicFileList">
            <!-- 使用ImageUpload组件 -->
            <ImageUpload 
              v-model="form.descriptionPicFileList" 
              :limit="4"
              :file-size="5"
              :file-type="['png', 'jpg', 'jpeg', 'gif']"
              ref="imageUploadRef"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">新增工单</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup name="MaintenanceAdd">
  import { getMaintenance, delMaintenance, addMaintenance } from "@/api/fang/maintenance"
  import ImageUpload from "@/components/ImageUpload/index.vue"
  import HouseSelector from "@/components/HouseSelector/index.vue"
  import TenantSelector from "@/components/TenantSelector/index.vue"
  
  const { proxy } = getCurrentInstance()
 
  const open = ref(false) 
  const imageUploadRef = ref(null)
  
  const data = reactive({
    form: {
      id: null,
      tenantUserId: null,
      tenantUserName: null,
      tenantUserPhone: null,
      houseId: null,
      houseName: null,
      tenantName: null,
      repairCreateTime: null,
      simpleDescription: null,
      detailDescription: null,
      descriptionPic: null,
      descriptionPicFileList: [],
      remark: null,
      maintenanceStatus: null,
      createBy: null,
      updateBy: null,
      createTime: null,
      updateTime: null
    },
    queryParams: { 
    },
    rules: {
      tenantUserPhone: [
        { 
          pattern: /^1[3-9]\d{9}$/, 
          message: "请输入正确的手机号码", 
          trigger: "blur" 
        }
      ]
    }
  })
  
  const { queryParams, form, rules } = toRefs(data)
   
  defineExpose({ openAddDialog }); 

  // 房源选择变化处理
  function handleHouseChange(houseId, houseOption) {
    if (houseId && houseOption) {
      form.value.houseName = houseOption.label
    } else {
      form.value.houseName = null
    }
  }


  // 租客选择变化处理
  function handleTenantChange(tenantId, tenantOption) {
    if (tenantId && tenantOption) {
      // 从label中解析姓名和手机号，格式：姓名-手机号
      const match = tenantOption.label.match(/^(.+)-(\d+)$/)
      if (match) {
        form.value.tenantUserName = match[1] // 姓名部分
        form.value.tenantUserPhone = match[2] // 手机号部分
      } else {
        form.value.tenantUserName = tenantOption.label || ''
        form.value.tenantUserPhone = tenantOption.phone || ''
      }
    } else {
      // 清空租客时，也清空姓名和手机号
      form.value.tenantUserName = ''
      form.value.tenantUserPhone = ''
    }
  }

  
  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }
  
  // 表单重置
  function reset() {
    form.value = {
      id: null,
      tenantUserId: null,
      tenantUserName: null,
      tenantUserPhone: null,
      houseId: null,
      houseName: null,
      tenantName: null,
      repairCreateTime: null,
      simpleDescription: null,
      detailDescription: null,
      descriptionPic: null,
      descriptionPicFileList: [],
      remark: null,
      maintenanceStatus: null,
      createBy: null,
      updateBy: null,
      createTime: null,
      updateTime: null
    }
    proxy.resetForm("maintenanceRef")
  }
  
  function openAddDialog(dataId) {
    reset()
    open.value = true
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["maintenanceRef"].validate(valid => {
      if (valid) {
        // 准备提交数据，确保字段名与API接口匹配
        const submitData = {
          houseId: form.value.houseId,
          tenantUserId: form.value.tenantUserId,
          tenantUserName: form.value.tenantUserName,
          tenantUserPhone: form.value.tenantUserPhone,
          repairCreateTime: form.value.repairCreateTime,
          simpleDescription: form.value.simpleDescription,
          detailDescription: form.value.detailDescription,
          descriptionPic: Array.isArray(form.value.descriptionPicFileList) ? form.value.descriptionPicFileList.map(item => item.id).join(',') : '', // 动态生成ID字符串
          descriptionPicFileList: form.value.descriptionPicFileList, // 新增对象数组
          remark: form.value.remark,
          maintenanceStatus: 1 // 默认状态为待处理
        }
        
        if (form.value.id != null) {
          submitData.id = form.value.id
          updateMaintenance(submitData).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            // 触发父组件刷新列表
            proxy.$emit('refresh')
          }).catch(error => {
            proxy.$modal.msgError("修改失败")
            console.error('修改维修工单失败:', error)
          })
        } else {
          addMaintenance(submitData).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            // 触发父组件刷新列表
            proxy.$emit('refresh')
          }).catch(error => {
            proxy.$modal.msgError("新增失败")
            console.error('新增维修工单失败:', error)
          })
        }
      }
    })
  }
  </script>

  <style scoped>
  </style>
  
  